// 常量定义
var APPFORM_TYPE = "APPFORM_TYPE";

//配置文件数据生成Panel对象
var applyFormInstance = {};
// 当前活动表单
var activateInstance = {};

// 初始化数据
for(var i = 0; i < 10; i++){
	var formNo = i + 1;
	// 一位的时候前面补0
	formNo = (formNo < 10) ? ("0" + formNo) : formNo.toString();
	applyFormInstance[formNo] = 
	{
		applyFormNo : formNo, // 表单编号01-10
		applyFormId : 0, // 表单Id
		applyFormType : APPFORM_TYPE + formNo, // 表单类型
		applyFormState : 0, // 页面状态：0：插入，1：更新
		customerId : '', // 选择客户（客户选择的客户Id）
		applyFormIsUpdated : false,// 表单数据是否有改动（表单一览是否要刷新）
		applyFormConfig : null, //配置文件数据
		applyFormPanel : null
	};
}

Ext.define('HIT.controller.ApplyFormController', {
	extend : 'Ext.app.Controller',
	models :[
	         'ApplyFormInvoiceDetailModel'
	         ,'ApplyFormInvoiceTaxDetailModel'
	         ,'ApplyFormListGridModel'
	         ,'MdataClient','MdataClientAddress'
	        ],
	stores :[
	         'ApplyFormInvoiceDetailStore'
	         ,'ApplyFormInvoiceTaxDetailStore'
	         ,'ApplyFormListGrid01Store' 
	         ,'ApplyFormListGrid02Store' 
	         ,'ApplyFormListGrid03Store' 
	         ,'ApplyFormListGrid04Store' 
	         ,'ApplyFormListGrid05Store'
	         ,'ApplyFormListGrid06Store' 
	         ,'ApplyFormListGrid07Store' 
	         ,'ApplyFormListGrid08Store' 
	         ,'ApplyFormListGrid09Store' 
	         ,'ApplyFormListGrid10Store'
	         ,'ApplyFormCustomerStore'
	         ,'ApplyFormCustomerAddrStore'
	         ],
	views  :[
	         'ApplyFormPanel'
	         ,'ApplyFormInvoiceDetail'
	         ,'ApplyFormInvoiceTaxDetail'
	         ,'ApplyFormListGrid01'
	         ,'ApplyFormListGrid02'
	         ,'ApplyFormListGrid03'
	         ,'ApplyFormListGrid04'
	         ,'ApplyFormListGrid05'
	         ,'ApplyFormListGrid06'
	         ,'ApplyFormListGrid07'
	         ,'ApplyFormListGrid08'
	         ,'ApplyFormListGrid09'
	         ,'ApplyFormListGrid10'
	         ,'ApplyFormCustomerPanel'
	         ,'ApplyFormCustomerAddrPanel'
	         ],

	/**
	 * application initialize not current page initialize
	 * 
	 * @param application
	 */
	init : function(application) {
		this.control({
			// 页面render前事件处理
			"applyformpanel" : {
				render: this.onPanelRenderEvent
			},
			"button" : {
				click : this.onButtonClick
			},
			"applyformlistgrid01" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid02" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid03" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid04" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid05" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent
			},
			"applyformlistgrid06" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid07" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid08" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid09" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			},
			"applyformlistgrid10" : {
				render: this.onGridRenderEvent,
				activate: this.onTabActivateEvent,
				beforeclose :this.onTabCloseEvent
			}
		});
	},

	/**
	 * 一览页面render事件
	 * 
	 * @param tabPanel 当前View对象
	 */
	onGridRenderEvent : function (tabPanel) {
		var applyFormType = APPFORM_TYPE + getEndStr(tabPanel.id, "tab-apply-form");
		var store = tabPanel.getStore();
		store.load({params:{applyFormType : applyFormType}});
	},

	/**
	 * 一览页面Activate事件
	 * 
	 * @param panel 当前View对象
	 */
	onTabActivateEvent : function (tabPanel) {
		var formNo = getEndStr(tabPanel.id, "tab-apply-form");
		activateInstance = applyFormInstance[formNo];
	},
	
	/**
	 * Tab 关闭事件
	 * @param tab
	 * @param e
	 */
	onTabCloseEvent :function(tabPanel, e){
		// 当前tab关闭
		var formNo = getEndStr(tabPanel.id, "tab-apply-form");
		// 初始化设置
		initApplyFormInstance(formNo);
	},
	
	/**
	 * 页面动态载入render事件
	 * 
	 * @param panel 当前View对象
	 */
	onPanelRenderEvent : function(panel) {
		this.applyFormRequestConfig(panel);
	},
	
	/**
	 * 从指定文件中获取配置对象
	 * 
	 * @param newPanel 当前View对象
	 */
	applyFormRequestConfig : function(newPanel){
		var url = 'resources/data/' + activateInstance.applyFormType + '.json';
		// 加载控件配置文件
		Ext.Ajax.request({
			url : url,
			success : function(response){
				var json = Ext.decode(response.responseText);
				if (json.success) {
					// 保存表达配置文件
					activateInstance.applyFormConfig = json;
					Share.AjaxRequest({
						url : ctx + '/getTaxCommonData',
	        	    	params : {},
	        	    	showMsg  : false,
	        	    	callback : function(dbJson) {
	        	    		dynamicAddViewComponent(newPanel, json, dbJson);
	        	    		// 数据设置
	        	    		applyFormRequestData();
	        	    	}
					});
				}
			}
		});
	},

	/**
	 * 按钮事件
	 * 
	 * @param button
	 * @param e
	 * @param options
	 */
	onButtonClick : function(button, e, options) {
		// ■ 类型一一览页面增加按钮
		if (startWith(button.id,'applyFormListAdd')) {
			activateInstance.applyFormState = 0;
			var aliasName = 'widget.applyformpanel';
			var panelId = 'panel-applyformpanel' + activateInstance.applyFormNo;
		    var panel = Ext.create(aliasName, {id : panelId});
		    var winId = 'win-applyformpanel' + activateInstance.applyFormNo;
		    createFormAddWin(winId, panel);
		    setPageMode(activateInstance.applyFormState);
		    // 清空添加页面中grid数据
		    var store = Ext.getCmp('applyFormGrid1').getStore();
			store.removeAll();
			var store2 = Ext.getCmp('applyFormGrid2').getStore();
			store2.removeAll();
			
			Ext.getCmp('hidden_form_id').setValue(0);
		}
		// ■ 类型一一览页面编辑按钮
		else if (startWith(button.id,'applyFormListEdit')) {
			var rowmodel = Ext.getCmp('tab-apply-form' + activateInstance.applyFormNo).getSelectionModel();
			if (rowmodel.hasSelection()) {
				if (rowmodel.getCount() != 1) {
	            	Share.ShowMessage("E0039","表单信息");
	                return;
	            }
				// 编辑状态
				activateInstance.applyFormId = rowmodel.getSelection()[0].get('FORM_ID');
				
				var submitStatus = 0;
				var ir_no = '';
				var create_user = '';
				var create_time = '';
				var formStatusStr = '';
				// 首先取得此表单的提交状态
				Ext.Ajax.request({
					url : 'getSubmitStatus',
					params : {
						formId : activateInstance.applyFormId
					},
					async : false,
					success : function(response) {
						s = response.responseText;
						json_f = Ext.JSON.decode(s);
						
						submitStatus = json_f.submitStatus;
						ir_no = json_f.form_no;
						create_user = json_f.create_user;
						create_time = json_f.create_time;
						formStatusStr = json_f.formStatusStr;
					}
				});
				var aliasName = 'widget.applyformpanel';
				var panelId = 'panel-applyformpanel' + activateInstance.applyFormNo;
			    var panel = Ext.create(aliasName, {id : panelId});
			    var winId = 'win-applyformpanel' + activateInstance.applyFormNo;
			    createFormAddWin(winId, panel);
			    
			    Ext.getCmp('hidden_form_id').setValue(rowmodel.getSelection()[0].get('FORM_ID'));
			    Ext.getCmp('ir_num').setValue(ir_no);
				Ext.getCmp('form_create_user').setValue(create_user);
				Ext.getCmp('apply_date').setValue(create_time);
				Ext.getCmp('ir_status').setValue(formStatusStr);
				activateInstance.applyFormState = 1;
				// 未提交状态
				if (submitStatus == 0) {
				    setPageMode(activateInstance.applyFormState);
				} 
				// 已提交
				else {
					Ext.getCmp("formpanel-save").setDisabled(true);
					Ext.getCmp("formpanel-save-new").setDisabled(true);
					Ext.getCmp("formpanel-submit").setDisabled(true);
					Ext.getCmp("formpanel-copy").setDisabled(false);
					Ext.getCmp("formpanel-recall-IR").setDisabled(false);
				}
			}else{
				Share.ShowMessage('I0008');
				return;
			}
		}
		// ■ 类型一一览页面删除按钮
		else if (startWith(button.id,'applyFormListDel')) {
			var tabPanel = Ext.getCmp('tab-apply-form' + activateInstance.applyFormNo);
			if (tabPanel == undefined) {
				return;
			}
			var selModel = tabPanel.getSelectionModel();
			//修改页面显示错误
            var row = selModel.getSelection(); 
			if (selModel.hasSelection()) {
				var model = selModel.getSelection();
				var formId = [];
				for(var i=0;i<model.length;i++){
            		formId.push(model[i].get('FORM_ID'));
                }
				var flag = false;
				Ext.Ajax.request({
					url : 'getSubFlag',
					method : 'POST',
					params : {
						formId : formId.join(",")
					},
					async : false,
					success : function(response) {
						s = response.responseText;
						json_f = Ext.JSON.decode(s);
						if (json_f.resultcode == 1) {
							flag = true;
						}
					}
				});
				if (flag) {
					Share.ShowMessage('I0089', "只能删除未提交的票据。");
					return;
				}
				Ext.MessageBox.confirm(Share.T('提示'),'是否确认删除？',function(btn){
					if(btn == 'yes'){
						Share.AjaxRequest({
							url : ctx + '/deleteApplyFormList',
							params : {
								formId : formId.join(",")
							},
							callback : function(json) {
								if (json.resultcode > 0) {
									// 刷新一览
									tabPanel.getStore().reload();
									//修改删除数据刷新数量
        							var toolbar = Ext.getCmp('ApplyFormListGrid' + activateInstance.applyFormNo + 'toolbar');
                                    var fromRecord = toolbar.getPageData().fromRecord;
                                    var toRecord = toolbar.getPageData().toRecord;
                                    if((toRecord-fromRecord + 1)==row.length){
                                    	toolbar.movePrevious();
                                    }
                                    Share.ShowMessage('I0006','删除');
								} else {
									Share.ShowMessage('I0007','删除');
								}
							}
						});
					}else{
						return;
					}
				});
			}else{
				Share.ShowMessage('I0008');
				return;
			}
		}
		// ■ 客户选择
		else if (button.id == 'cust_choose') {
			var aliasName = 'widget.applyformcustomerpanel';
		    var panel = Ext.create(aliasName);
		    var winId = 'win-applyformcustomerpanel';
		    createCustomerListWin(winId, panel);
		}
		// ■ 收件人选择
		else if (button.id == 'receive_choose') {
			var aliasName = 'widget.applyformcustomeraddrpanel';
		    var panel = Ext.create(aliasName);
		    var winId = 'win-applyformcustomeraddrpanel';
		    createCustomerAddrListWin(winId, panel);
		    
		    /* grid信息 */
			var store = Ext.getCmp('applyFormCustomerAddrPanel').getStore();
			store.removeAll();
			store.on('beforeload', function(store) {
				Ext.apply(store.proxy.extraParams , {mainId : activateInstance.customerId});
			});
			store.load();
		}
		// ■ 附件下载
		else if (startWith(button.id, 'download_file')) {
			downloadApplyformAttacheFile(getEndStr(button.id, 'download_file'));
		}
		// ■ 附件删除
		else if (startWith(button.id, 'delete_file')) {
			deleteApplyformAttacheFile(getEndStr(button.id, 'delete_file'));
		}
		// ■ 增加明细行
		else if (startWith(button.id, 'add_datail')) {
			addDetail(getEndStr(button.id, 'add_datail'));
		}
		// ■ 删除明细行
		else if (startWith(button.id, 'del_datail')) {
			delDetail(getEndStr(button.id, 'del_datail'));
		} 
		// ■ 表单一览查询按钮
		else if (searchBtn(button.id, 'form_list_search')) {
			var id = button.id.substr(16, 18);
			var formno = Ext.getCmp('form_list_docno' + id).getValue();
			var custname = Ext.getCmp('form_list_custname' + id).getValue();
			var formstatus = Ext.getCmp('form_list_status' + id).getValue();
			var applydate = Ext.getCmp('form_appply_date' + id).getValue();
			
			var store = Ext.getCmp('tab-apply-form' + id).getStore();
			store.currentPage = 1;
      		store.removeAll();
      		store.on('beforeload', function(store) {
     			Ext.apply(store.proxy.extraParams , {
     				formtype : 'APPFORM_TYPE01' + id,
     				formno : formno,
     				custname : custname,
     				formstatus : formstatus,
     				applydate : applydate
     			});
      		});
      		store.load();
		}
	}
});

/**
 * 表单创建
 * 
 * @param winid
 * @param panel
 */
function createFormAddWin(winid, panel) {
	// 创建添加窗口
	var win = Ext.create('Ext.window.Window', {
        id        : winid,
        title 	  : Share.T('自定义表单添加'),
        resizable : true,
        closable  : true,
        width 	  : window.screen.width * 0.8,
        height    : window.screen.height * 0.8,
        layout    : 'fit',
        plain     : true,
        modal 	  : true,
        items     : panel,
        buttons   : [ {
            text : Share.T('保存'),
			id : 'formpanel-save',
			width : 70,
			handler : function() {
				// 验证处理
				if(!viewValid()){
					Share.ShowMessage('I0007',Share.T('验证'));
					return;
				}
				var formData = getApplyFormControl();
				Share.AjaxRequest({
					url : ctx + '/saveApplyForm', 
	       			params : {data : Ext.encode(formData)},
	       			callback : function(json) {
	       				// 上传附件
	       				uploadApplyformAttacheFile(json.formId,function(success){
	       					// 上传附件成功
	       					if(success){
	       						activateInstance.applyFormIsUpdated = true;
//			       				Share.ShowMessage('I0006',Share.T('保存'));
			       				Ext.Msg.alert("提示", Share.T('保存成功'));
			       				win.close();
	       					} else {
	       						activateInstance.applyFormIsUpdated = true;
			       				Share.ShowMessage('提示',Share.T('附件上传失败'));
	       					}
	       				});
	       			}
				});
			}
        }, {
        	text : Share.T('保存并新建'),
			id : 'formpanel-save-new',
			width : 70,
			handler : function() {
				// 验证处理
				if(!viewValid()){
					Share.ShowMessage('I0007',Share.T('验证'));
					return;
				}
				var formData = getApplyFormControl();
				Share.AjaxRequest({
					url : ctx + '/saveApplyForm', 
	       			params : {data : Ext.encode(formData)},
	       			callback : function(json) {
	       				// 上传附件
	       				uploadApplyformAttacheFile(json.formId,function(success){
		       				// 表单重置
		       				Ext.getCmp('controlForm01').getForm().reset();
		       				Ext.getCmp('controlForm02').getForm().reset();
		       				Ext.getCmp('controlForm03').getForm().reset();
		       				
		       				// 上传附件一览清空
		    				var formConfig = activateInstance.applyFormConfig["ApplyFormConfig"];
		    				var rowForm = formConfig["visibleattache"];
		    				for(i in rowForm){
		    					var key = rowForm[i]["id"];
		    					var ids = getEndStr(key,"attache");
		    					clearAttcheFileControl(ids);
		    				}
		       				
		       				// 发票一览重置
		       				forms = formConfig['visibleinvoice'];
		       				for(var i in forms){
		       					var key = forms[i]['id'];
		       					var gridId = 'applyFormGrid' + getEndStr(key, 'invoice');
		       					var store = Ext.getCmp(gridId).getStore();
		       					store.removeAll();
		       				}
		       				// 设置成新建状态
		       				activateInstance.applyFormState = 0;
		       				activateInstance.applyFormId = 0;
		       				activateInstance.customerId = '';
		       				activateInstance.applyFormIsUpdated = true;
		       				
			       			// 不管上传附件成功与否动reset表单
	       					if(success){
			       				Share.ShowMessage('I0006',Share.T('保存并新建'));
	       					} else {
			       				Share.ShowMessage('提示',Share.T('附件上传失败'));
	       					}
	       				});
	       			}
				});
			}
        }, {
            text : Share.T('提交'),
			id : 'formpanel-submit',
			width : 70,
			handler : function() {
				// 验证处理
				if(!viewValid()){
					Share.ShowMessage('I0007',Share.T('验证'));
					return;
				}
				activateInstance.applyFormId = Ext.getCmp('hidden_form_id').getValue();
				// 首先保存或修改
				var formData = getApplyFormControl();
				Share.AjaxRequest({
					url : ctx + '/saveApplyForm',
	       			params : {data : Ext.encode(formData)},
	       			callback : function(json) {
	       				// 上传附件
	       				uploadApplyformAttacheFile(json.formId,function(success){
	       					// 上传附件成功
	       					if(success){
	       						Ext.getCmp('hidden_form_id').setValue(json.formId);
	       						activateInstance.applyFormId = json.formId;
	       						// 将新生成的formId给全局变量
	       						activateInstance.applyFormIsUpdated = true;
	       						Share.AjaxRequest({
	       							url : ctx + '/submitApplyForm',
	       			       			params : {formId : json.formId},
	       			       			callback : function(json) {
	       			       				// 提交成功
	       			       				if(json.result == 0){
	       			       					Share.ShowMessage('I0089', json.retstr);
	       			       					win.close();
	       			       				} 
	       			       				// 提交失败
	       			       				else if (json.result == 1) {
	       			       					// 提交失败将状态改为修改状态
		       			       				activateInstance.applyFormState = 1;
			       			 			    setPageMode(activateInstance.applyFormState);
			       			 			    
	       			       					var errorwin = Ext.create('Ext.window.Window', {
	       									    title: Share.T('提交失败'),
	       									    height : 240,
	       									    width : 353,
	       									    modal :true,
	       									    layout : {
	       											type : 'absolute'
	       										},
	       									    items: [ {
	       									        xtype : 'textarea',
	       									        width : 310,
	       									        height : 150,
	       									        id : 'submit_error_msg',
	       									        x : 15,
	       									        y : 15
	       									    } ],
	       									    buttons : [ {
	       									    	xtype : 'button',
	       									    	text : Share.T('确定'),
	       									    	handler : function() {
	       									    		errorwin.close();
	       									    	}
	       									    },{
	       									    	xtype : 'button',
	       									    	text : Share.T('复制信息'),
	       									    	handler : function() {
	       									    		var error_msg = Ext.getCmp('submit_error_msg');
	       									    		
	       									    		if (window.clipboardData) {
	       									    			window.clipboardData.clearData();
	       									    			window.clipboardData.setData("Text", error_msg.getValue());
	       									    			Ext.Msg.alert('提示', Share.T('复制成功。'), function(){
	       									    				errorwin.close();
	       							       					});
	       									    		} else {
	       									    			Ext.Msg.alert('提示', Share.T('此浏览器不支持此功能，请使用Ctrl+C复制。'), function(){
	       									    				error_msg.selectText();
	       							       					});
	       									    		}
	       									    	}
	       									    } ]
	       									}).show();
	       			       					Ext.getCmp('submit_error_msg').setValue(json.retstr);
	       			       				} 
	       			       				// 有错但可以继续提交
	       			       				else if (json.result == 2) {
	       			       					// 提交失败将状态改为修改状态
		       			       				activateInstance.applyFormState = 1;
			       			 			    setPageMode(activateInstance.applyFormState);
		       			       				var errorwin = Ext.create('Ext.window.Window', {
	       									    title: Share.T('继续提交'),
	       									    height : 240,
	       									    width : 353,
	       									    modal :true,
	       									    layout : {
	       											type : 'absolute'
	       										},
	       									    items: [ {
	       									        xtype : 'textarea',
	       									        width : 310,
	       									        height : 150,
	       									        id : 'submit_error_continue',
	       									        x : 15,
	       									        y : 15
	       									    } ],
	       									    buttons : [ {
	       									    	xtype : 'button',
	       									    	text : Share.T('确定'),
	       									    	handler : function() {
	       									    		errorwin.close();
	       									    		// 继续提交操作
	       									    		Share.AjaxRequest({
	       					       							url : ctx + '/submitFormContinue',
	       					       			       			params : {formId : activateInstance.applyFormId},
	       					       			       			callback : function(json) {
	       					       			       				// 提交成功
	       					       			       				if(json.resultcode == 0){
	       					       			       					activateInstance.applyFormIsUpdated = true;
	       					       			       					Share.ShowMessage('I0089', json.retstr);
	       					       			       					win.close();
	       					       			       				} else {
	       					       			       					Share.ShowMessage('I0089', json.retstr);
		   					       			       					win.close();
	       					       			       				}
	       					       			       			}
	       									    		});
	       									    	}
	       									    }, {
	       									    	xtype : 'button',
	       									    	text : Share.T('取消'),
	       									    	handler : function() {
	       									    		activateInstance.applyFormIsUpdated = true;
	       									    		errorwin.close();
	       									    	}
	       									    },{
	       									    	xtype : 'button',
	       									    	id : 'copytest',
	       									    	text : Share.T('复制信息'),
	       									    	listeners : {
	       									    		click : function() {
		       									    		var error_msg = Ext.getCmp('submit_error_continue');
		       									    		
		       									    		if (window.clipboardData) {
		       									    			window.clipboardData.clearData();
		       									    			window.clipboardData.setData("Text", error_msg.getValue());
		       									    			Ext.Msg.alert('提示', Share.T('复制成功。'), function(){
		       									    				errorwin.close();
		       							       					});
		       									    		} else {
		       									    			Ext.Msg.alert('提示', Share.T('此浏览器不支持此功能，请使用Ctrl+C复制。'), function(){
		       									    				error_msg.selectText();
		       							       					});
		       									    		}
		       									    	}
	       									    	}
	       									    } ]
	       									}).show();
	       			       					Ext.getCmp('submit_error_continue').setValue(json.retstr);
	       			       				}
	       			       			}
	       						});
	       					} else {
	       						activateInstance.applyFormIsUpdated = true;
	       						Share.ShowMessage('I0007', '提交');
	       					}
	       				});
	       			}
				});
			}
        }, {
            text : Share.T('复制'),
			id : 'formpanel-copy',
			width : 70,
			handler : function(button) {
				// 状态修改为新建
				activateInstance.applyFormState = 0;
				
				Ext.getCmp("formpanel-save").setDisabled(false);
				Ext.getCmp("formpanel-save-new").setDisabled(false);
				Ext.getCmp("formpanel-submit").setDisabled(false);
				button.setDisabled(true);
				Ext.getCmp("formpanel-recall-IR").setDisabled(true);
				
				// 上传附件一览清空
				var formConfig = activateInstance.applyFormConfig["ApplyFormConfig"];
				var rowForm = formConfig["visibleattache"];
				for(i in rowForm){
					var key = rowForm[i]["id"];
					var ids = getEndStr(key,"attache");
					clearAttcheFileControl(ids);
				}
				Share.ShowMessage('I0006',Share.T('复制'));
			}
        }, {
            text : Share.T('撤回IR'),
			id : 'formpanel-recall-IR',
			width : 70,
			handler : function() {
				// 验证处理
				if(!viewValid()){
					Share.ShowMessage('I0007',Share.T('验证'));
					return;
				}
				Share.AjaxRequest({
					url : ctx + '/rollBackApplyForm',
					params : {formId : activateInstance.applyFormId},
	       			callback : function(json) {
	       				if(json.result == 0){
	       					activateInstance.applyFormIsUpdated = true;
	       					Share.ShowMessage('I0089', json.retstr);
       						win.close();
	       				} else if (json.result == 1) {
	       					var errorwin = Ext.create('Ext.window.Window', {
							    title: Share.T('继续撤回'),
							    height : 240,
							    width : 353,
							    modal :true,
							    layout : {
									type : 'absolute'
								},
							    items: [ {
							        xtype : 'textarea',
							        width : 310,
							        height : 150,
							        id : 'roll_error_msg',
							        x : 15,
							        y : 15
							    } ],
							    buttons : [ {
							    	xtype : 'button',
							    	text : Share.T('确定'),
							    	handler : function() {
							    		Share.AjaxRequest({
											url : ctx + '/continueRollBackApplyForm',
											params : {formId : activateInstance.applyFormId},
							       			callback : function(json) {
							       				if(json.resultcode == 0){
							       					activateInstance.applyFormIsUpdated = true;
							       					Share.ShowMessage('I0089', json.retstr);
							       					errorwin.close();
						       						win.close();
							       				} else {
							       					Share.ShowMessage('I0089', json.retstr);
							       					errorwin.close();
						       						win.close();
							       				}
							       			}
							    		});
							    	}
							    }, {
							    	xtype : 'button',
							    	text : Share.T('取消'),
							    	handler : function() {
							    		activateInstance.applyFormIsUpdated = true;
							    		errorwin.close();
							    	}
							    }, {
							    	xtype : 'button',
							    	text : Share.T('复制信息'),
							    	handler : function() {
							    		var error_msg = Ext.getCmp('roll_error_msg');
							    		
							    		if (window.clipboardData) {
							    			window.clipboardData.clearData();
							    			window.clipboardData.setData("Text", error_msg.getValue());
							    			Ext.Msg.alert('提示', Share.T('复制成功。'), function(){
							    				errorwin.close();
					       					});
							    		} else {
							    			Ext.Msg.alert('提示', Share.T('此浏览器不支持此功能，请使用Ctrl+C复制。'), function(){
							    				error_msg.selectText();
					       					});
							    		}
							    	}
							    } ]
	       					}).show();
	       					Ext.getCmp('roll_error_msg').setValue(json.retstr);
	       				} else if (json.result == 2) {
	       					activateInstance.applyFormIsUpdated = true;
	       					Share.ShowMessage('I0089', json.retstr);
       						win.close();
	       				}
	       			}
				});
			}
        }],
        listeners:{
        	beforeclose : function(){
        		// 关闭表单后刷新一览
        		if(activateInstance.applyFormIsUpdated){
        			getListStore().reload();
        		}
        		// 重新初始化设置
        		initApplyFormInstance(activateInstance);
        	}
        }
    }).show();
}

/**
 * 设置页面状态
 * 
 * @param state
 */
function setPageMode(state){
	if (state == 0 || state == 1) {
		// button状态设置
		Ext.getCmp("formpanel-save").setDisabled(state != 0 && state != 1);
		Ext.getCmp("formpanel-save-new").setDisabled(state != 0 && state != 1);
		Ext.getCmp("formpanel-copy").setDisabled(state != 1);
		Ext.getCmp("formpanel-recall-IR").setDisabled(state = 1);
	}
}

/**
 * 表单一览获取
 */
function getListStore(){
	var tabPanel = Ext.getCmp('tab-apply-form' + activateInstance.applyFormNo);
	return tabPanel.getStore();
}

/**
 * 客户主数据一览：客户基本信息一览
 * 
 * @param winid
 * @param panel
 */
function createCustomerListWin(winid, panel) {
	// 客户基本信息一览
	var win = Ext.create('Ext.window.Window', {
        id        : winid,
        title 	  : Share.T('客户选择'),
        resizable : false,
        closable  : true,
        width 	  : 500,
        height    : 500,
        layout    : 'fit',
        plain     : true,
        modal 	  : true,
        items     : panel,
        buttons   : [ {
            text : Share.T('确定'),
			id : 'formpanel-customer-select',
			width : 70,
			handler : function() {
				var rowmodel = Ext.getCmp('applyFormCustomerPanel').getSelectionModel();
				activateInstance.customerId = rowmodel.getSelection()[0].get('id');
				Share.AjaxRequest({
					url : ctx + '/getMdataCustomerDetail', 
	       			params : {customerId : activateInstance.customerId},
	       			callback : function(json) {
//	       				Ext.getCmp("CTRL11_02").setValue(json["id"]);
//	       				Ext.getCmp("CTRL11_03").setValue(json["code"]);
	       				Ext.getCmp("CTRL11_02").setValue(json["client_supplier"]);
	       				Ext.getCmp("CTRL11_03").setValue(json["tax_code"]);
	       				Ext.getCmp("CTRL12_02").setValue(json["bank"]);
	       				Ext.getCmp("CTRL12_03").setValue(json["bank_account"]);
	       				Ext.getCmp("CTRL13_02").setValue(json["address"]);
	       				Ext.getCmp("CTRL13_03").setValue(json["tel"]);
	       				Ext.getCmp("CTRL14_02").setValue(json["ref01"]);
	       				Ext.getCmp("CTRL14_03").setValue(json["time"]);
	       				Ext.getCmp("CTRL15_05").setValue(true);
	    				win.close();
	       			}
       			});
			}
        },{
            text : Share.T('取消'),
			id : 'formpanel-customer-cancel',
			width : 70,
			handler : function() {
				win.close();
			}
        }]
    }).show();
}

/**
 * 客户主数据一览：收件人基本信息一览
 * 
 * @param winid
 * @param panel
 */
function createCustomerAddrListWin(winid, panel) {
	// 客户基本信息一览
	var win = Ext.create('Ext.window.Window', {
        id        : winid,
        title 	  : Share.T('收件人信息选择'),
        resizable : false,
        closable  : true,
        width 	  : 800,
        height    : 500,
        layout    : 'fit',
        plain     : true,
        modal 	  : true,
        items     : panel,
        buttons   : [ {
            text : Share.T('确定'),
			id : 'formpanel-customerAddr-select',
			width : 70,
			handler : function() {
				var rowmodel = Ext.getCmp('applyFormCustomerAddrPanel').getSelectionModel();
				contactId = rowmodel.getSelection()[0].get('id');
				Share.AjaxRequest({
					url : ctx + '/getMdataCustomerAddrDetail', 
	       			params : {contactId : contactId},
	       			callback : function(json) {
//	       				for(var cKey in json){
//	       					Ext.getCmp(cKey).setValue(json[cKey]);
//	       				}
	       				//Ext.getCmp("CTRL11_02").setValue(json["id"]);
	       				Ext.getCmp("CTRL18_02").setValue(json["recv_ticket"]);
	       				Ext.getCmp("CTRL18_03").setValue(json["recv_company"]);
	       				Ext.getCmp("CTRL19_02").setValue(json["recv_address"]);
	       				Ext.getCmp("CTRL19_03").setValue(json["recv_tel"]);
	       				Ext.getCmp("CTRL20_02").setValue(json["recv_zipCode"]);
	       				Ext.getCmp("CTRL20_03").setValue(json["ref01"]);
	       				Ext.getCmp("CTRL21_02").setValue(json["city"]);
	       				Ext.getCmp("CTRL22_05").setValue(true);
	       				Ext.getCmp("CTRL23_05").setValue(true);
	    				win.close();
	       			}
       			});
				win.close();
			}
        },{
            text : Share.T('取消'),
			id : 'formpanel-customerAddr-cancel',
			width : 70,
			handler : function() {
				win.close();
			}
        }]
    }).show();
}

/**
 * 动态配置View组件
 * 从指定文件中获取配置对象
 * 
 * @param newPanel 当前View对象
 * @param json 配置的JSON对象
 * @param dbJson 数据库JSON对象
 */
function dynamicAddViewComponent(newPanel, json, dbJson){
	// 循环每一个控件设置控件状态及样式等属性
	var formConfig = {};
	formConfig = json["ApplyFormConfig"];
	// 1-42控件
	var fieldset = null;
	var rowForm = [];
	for(var formKey in formConfig){
		// 把组件Visible放到最后执行
		if(startWith(formKey,"visible")){
			continue;
		}
		fieldset = newPanel.down("#"+formKey);
		rowForm = formConfig[formKey];
		// 创建FieldSet
		for(i in rowForm){
			rowCtrl = rowForm[i];
			// 创建FieldSet行集合
			var fieldsetRow = new Ext.form.Panel({
				id : rowCtrl["id"],
				layout : "column",
				margin : '10 0',
				border : false
			});
			// 创建FieldSet列控件
			for(var j in rowCtrl["items"]) {
				var colCtrl = rowCtrl["items"][j];
				var c = null;
				switch(colCtrl["xtype"]){
					case "label":
						c = new Ext.form.Label({
							id : colCtrl["id"],
							text : colCtrl["text"],
							style : 'font-width:12px; color:#4F94CD;',
							width : 450
						});
						break;
					case "textfield":
						if(colCtrl["isNumber"]){
							c = new Ext.form.field.Number({
								id : colCtrl["id"],
								msgTarget  : 'side',
								fieldLabel : colCtrl["text"],
								maxLength  : colCtrl["maxLength"],
								labelAlign : 'right',
								allowBlank : !colCtrl["isNeed"],
								hideTrigger : true,
								width : 450,
								labelWidth : 250
							});
						} else if(colCtrl["isDate"]){
							c = new Ext.form.field.Date({
								id : colCtrl["id"],
								msgTarget  : 'side',
								fieldLabel : colCtrl["text"],
								labelAlign : 'right',
								allowBlank : !colCtrl["isNeed"],
								width : 450,
								format : 'Y-m-d',
								labelWidth : 250
							});
						} else {
							c = new Ext.form.field.Text({
								id : colCtrl["id"],
								msgTarget  : 'side',
								fieldLabel : colCtrl["text"],
								maxLength  : colCtrl["maxLength"],
								labelAlign : 'right',
								allowBlank : !colCtrl["isNeed"],
								width : 450,
								labelWidth : 250
							});
						}
						break;
					case "checkbox":
						c = Ext.create('Ext.form.Checkbox', {
							id : colCtrl["id"],
							fieldLabel : colCtrl["text"],
							labelAlign : 'right',
							width : 450,
							labelWidth : 250
						});
						break;
					case "combobox":
						// 获取ComboBox数据
						var comboData = dbJson[colCtrl["codeKey"]];
						if(!comboData){
							comboData = [];
						}
						// 获取默认值
						var defaultValue = "";
						for(var i in comboData){
							if(1 == comboData[i]["isDefaultValue"]){
								defaultValue = comboData[i]["uniqueKey"];
								break;
							}
						}
						c = Ext.create('Ext.form.ComboBox', {
							id : colCtrl["id"],
						    fieldLabel: colCtrl["text"],
							labelAlign : 'right',
							width : 450,
							labelWidth : 250,
						    displayField: 'codeValue',
						    valueField: 'uniqueKey',
						    queryMode : 'local',
							store : new Ext.data.JsonStore({
								fields : ['codeValue','uniqueKey'], 
		    					data : comboData
		        	        }),
		        	        listeners:{
	        	        		beforerender: function(box, eOpts){
        	        				box.select(defaultValue);
        	        			}
		        	        }
						});
						break;
				}
				fieldsetRow.add(c);

			}// for col
			// 有值的时候add进去
			if(fieldsetRow.items.length > 0){
				fieldset.add(fieldsetRow);
			}
		}// end control
	}
	// 强行把显示放到最后出来
	var controlVisible = formConfig['visiblebutton'];
	for(var i in controlVisible){
		newPanel.down("#" + controlVisible[i]['id']).setVisible(true);
	}
	controlVisible = formConfig['visibleattache'];
	for(var i in controlVisible){
		newPanel.down("#" + controlVisible[i]['id']).setVisible(true);
	}
	controlVisible = formConfig['visibleinvoice'];
	for(var i in controlVisible){
		newPanel.down("#" + controlVisible[i]['id']).setVisible(true);
	}
}

/**
 * 获取数据对象
 * 
 * @param newPanel 当前View对象
 */
function applyFormRequestData() {
	// 编辑mode设置数据
	if(activateInstance.applyFormState == 1 && activateInstance.applyFormId){
		// 设置数据设置值
		setApplyFormControl(activateInstance.applyFormId);
		// 设置Grid数据
		setApplyFormInvoiceGrid(activateInstance.applyFormId);
		setApplyFormInvoiceTaxGrid(activateInstance.applyFormId);
	}
}

/**
 * 循环设置配置中显示对象
 * 
 * @param applyFormId
 */
function setApplyFormControl(applyFormId){
	// DB中获取的数据，写入到页面上
	Share.AjaxRequest({
		url : ctx + '/getApplyForm',
    	params : {formId : applyFormId},
    	showMsg  : false,
    	callback : function(jsonData) {
    		var key = "";
    		var formConfig = activateInstance.applyFormConfig["ApplyFormConfig"];
    		// 循环获取配置中显示对象
    		for(var formKey in formConfig){
    			rowForm = formConfig[formKey];
    			switch(formKey){
    			case "visiblebutton":
    				break;
    			case "visibleattache":
    				var arr = jsonData["applyFormAttacheFile"];
    				for(i in rowForm){
    					rowCtrl = rowForm[i];
    					key = rowCtrl["id"];
    					var ids = getEndStr(key,"attache");
    					// 设置值和显示状态样式
    					if(arr && arr.length > i){
    						setAttcheFileControl(ids, arr[i]);
    					}
    				}
    				break;
    			case "visibleinvoice":
    				// 对于Grid单独处理
    				break;
    			default:
	    			for(i in rowForm){
	    				rowCtrl = rowForm[i];
	    				for(var j in rowCtrl["items"]) {
	    					// 获取指定对象
	    					colCtrl = rowCtrl["items"][j];
	    					key = colCtrl["id"];
	    					cmp = Ext.getCmp(key);
	    					switch(colCtrl["xtype"]){
	    						case "label":
	    							cmp.text = jsonData[key];
	    							break;
	    						case "textfield":
	    						case "combobox":
	    							cmp.setValue(jsonData[key]);
	    							break;
	    						case "checkbox":
	    							cmp.setValue(jsonData[key]=="1" ? true : false);
	    							break;
	    						default:
	    							break;
	    					}//switch
	    				}
	    			}//for
    			break;
    			}
    		}
    	}// callback
	});
}

/**
 * 设置发票一览
 * @param applyFormId
 */
function setApplyFormInvoiceGrid(applyFormId){
	/* grid信息 */
	var store = Ext.getCmp('applyFormGrid1').getStore();
	store.removeAll();
	store.on('beforeload', function(store) {
		Ext.apply(store.proxy.extraParams , {formId : applyFormId});
	});
	store.load(function(_records, _operation, success){
		if (_records.length <= 0) {
	    	Ext.getCmp('del_datail1').setVisible(false);
	    }else{
	    	Ext.getCmp('del_datail1').setVisible(true);
	    }
	});
}

/**
 * 设置营业税发票一览
 * @param applyFormId
 */
function setApplyFormInvoiceTaxGrid(applyFormId){
	/* grid信息 */
	var store = Ext.getCmp('applyFormGrid2').getStore();
	store.removeAll();
	store.on('beforeload', function(store) {
		Ext.apply(store.proxy.extraParams , {formId : applyFormId});
	});
	store.load(function(_records, _operation, success){
		if (_records.length <= 0) {
	    	Ext.getCmp('del_datail2').setVisible(false);
	    }else{
	    	Ext.getCmp('del_datail2').setVisible(true);
	    }
	});
}

/**
 * 循环获取配置中显示对象
 */
function getApplyFormControl(){
	// 页面上获取的数据，写入到DB中
	// 分为两个部分，表单(key=applyForm)和一览(key=applyFormGrid1,applyFormGrid2)
	var jsonData = {};
	// 表单的文本等数据对象，除了Grid一览
	var formData = {};
	jsonData["applyForm"] = formData;
	jsonData["applyFormGrid1"] = {};
	jsonData["applyFormGrid2"] = {};
	var rowForm = [];
	var rowCtrl = {};
	var colCtrl = {};
	var cmp = {};// 控件对象
	var key = "";
	// 设置表单Id
	jsonData['formId'] = activateInstance.applyFormId;
	// 设置状态：update，insert...
	jsonData['applyFormState'] = activateInstance.applyFormState;
	// 设置表单类型
	jsonData['applyFormType'] = activateInstance.applyFormConfig['ApplyFormType'];
	var formConfig = activateInstance.applyFormConfig["ApplyFormConfig"];
	// 循环获取配置中显示对象
	for(var formKey in formConfig){
		rowForm = formConfig[formKey];
		switch(formKey){
		case "visiblebutton":
			break;
		case "visibleattache":
			for(i in rowForm){
				rowCtrl = rowForm[i];
				key = rowCtrl["id"];
				var remarkId = "remark" + getEndStr(key,"attache");
				cmp = Ext.getCmp(remarkId);
				formData[remarkId] = cmp.getValue();
			}
			break;
		case "visibleinvoice":
			for(i in rowForm){
				// 获取Grid的数据一览 ，这里动态设置没有意义，
				// 后台还是通过固定key来取对象，写入DB。不过还是动态设置
				// 数据结构跟DB结构有关，因为Grid采用了两张表，所以要分别制定。
				// TODO只是修改的部分
				rowCtrl = rowForm[i];
				key = rowCtrl["id"];
				var gridId = 'applyFormGrid' + getEndStr(key, 'invoice');
				jsonData[gridId] = getApplyFormGridData(gridId);
			}
			break;
		default:
			// 表单
			for(i in rowForm){
				rowCtrl = rowForm[i];
				for(var j in rowCtrl["items"]) {
					// 获取指定对象
					colCtrl = rowCtrl["items"][j];
					key = colCtrl["id"];
					cmp = Ext.getCmp(key);
					switch(colCtrl["xtype"]){
						case "label":
							formData[key] = cmp.text;
							break;
						case "textfield":
							if(cmp.isXType("datefield")){
								formData[key] = dateFormat(cmp.getValue());
							}else{
								formData[key] = cmp.getValue();
							}
							break;
						case "combobox":
							formData[key] = cmp.getValue();
							break;
						case "checkbox":
							formData[key] = (cmp.getValue() ? 1 : 0);
							break;
						default:
							break;
					}
				}
			}// end for
			break;
		}
	}
	return jsonData;
}

/**
 * 获取指定Grid的一览数据
 * 
 * @param storeId
 */
function getApplyFormGridData(storeId){
	var store = Ext.getCmp(storeId).getStore();
	var gridData = [];
	for(var i = 0; i < store.getCount(); i++){
		var grid_Row_item = {};
		grid_Row_item['goodsName'] = store.getAt(i).get('goodsName');
		grid_Row_item['goodsModel'] = store.getAt(i).get('goodsModel');
		grid_Row_item['goodsUnit'] = store.getAt(i).get('goodsUnit');
		
		var quantity = store.getAt(i).get('quantity') + ""; 
		grid_Row_item['quantity'] = quantity == "" ? "0" : quantity;
		
		var priceUnit = store.getAt(i).get('priceUnit') + "";  
		grid_Row_item['priceUnit'] = priceUnit == "" ? "0" : priceUnit;
		
		var amount = store.getAt(i).get('amount') + ""; 
		grid_Row_item['amount'] = amount == "" ? "0" : amount;
		
		var taxRate = store.getAt(i).get('taxRate') + "";  
		grid_Row_item['taxRate'] = taxRate == "" ? "0" : taxRate;

		var remark = store.getAt(i).get('remark') + "";
		grid_Row_item['remark'] = remark == "" ? "0" : remark;
		
		var taxAmount = store.getAt(i).get('taxAmount') + ""; 
		grid_Row_item['taxAmount'] = taxAmount == "" ? "0" : taxAmount;
		gridData.push(grid_Row_item);
	}
	return gridData;
}

/**
 * 上传附件（批量上传，先保存表单获取Id，在发送提交请求）
 * 
 * @param id
 */
function uploadApplyformAttacheFile(formId, callback){
	var form = Ext.getCmp('attacheForm').getForm();
	form.submit({
		// 参数formId，当前状态
		url: ctx + '/uploadApplyformAttacheFile',
		method:'POST',
		params:{formId : formId},
		waitMsg: '上传中...',
		success: function() {
			if(callback){
				// 上传成功
				callback(true);
			}
        },
        failure: function() {
    		if(callback){
    			// 上传失败
				callback(false);
			}
        }
	});
}

/**
 * 删除附件
 * 
 * @param ids
 */
function deleteApplyformAttacheFile(ids){
	var formId = activateInstance.applyFormId;
	var attacheFileName = Ext.getCmp("attacheFileName" + ids).getValue();
	var attacheFileId = Ext.getCmp("attacheFileId" + ids).getValue();
	
	Ext.MessageBox.confirm(Share.T('提示'),'是否确认删除附件：' + attacheFileName + '？',function(btn){
		if(btn == 'yes'){
			Share.AjaxRequest({
				url : ctx + '/deleteApplyformAttacheFile',
				params : {formId : formId, attacheFileName : attacheFileName, attacheFileId:attacheFileId},
				showMsg  : false,
				callback : function(json) {
					// 设置显示样式
					clearAttcheFileControl(ids);
				}
			});
		}
	});
}

/**
 * 下载附件
 * 
 * @param ids
 */
function downloadApplyformAttacheFile(ids){
	var formId = activateInstance.applyFormId;
	var attacheFileName = Ext.getCmp("attacheFileName" + ids).getValue();

	Share.AjaxRequest({
		url : ctx + '/getApplyformAttacheFilePath',
    	params : {formId : formId, attacheFileName : attacheFileName},
    	showMsg  : false,
    	callback : function(jsonData) {
    		if(jsonData.success){
    			var href = ctx + '/downloadApplyformAttacheFile?formId='+formId + '&attacheFileName=' + encodeURI(encodeURI(attacheFileName));
    			window.location.href = href;
    		} else {
    			Share.ShowMessage('I0006',"下载失败，文件不存在");
    		}
    	}
	});
	
}

/**
 * 初始化附件控件
 * 
 * @param ids
 */
function clearAttcheFileControl(ids){
	// 设置显示样式
	Ext.getCmp("attacheFileId" + ids).setValue("");
	Ext.getCmp("remark" + ids).setValue("");
	Ext.getCmp("attacheFileName" + ids).setValue("");
	Ext.getCmp('attacheFileName' + ids).setVisible(false);
	Ext.getCmp('filefield' + ids).setVisible(true);
	Ext.getCmp('delete_file' + ids).setVisible(false);
	Ext.getCmp('download_file' + ids).setVisible(false);
}
/**
 * 设置附件控件
 * 
 * @param ids
 * @param obj
 */
function setAttcheFileControl(ids, obj){
	// 设置显示样式
	Ext.getCmp("attacheFileId" + ids).setValue(obj["attacheFileId"]);
	Ext.getCmp("remark" + ids).setValue(obj["remark"]);
	Ext.getCmp("attacheFileName" + ids).setValue(obj["attacheFile"]);
	Ext.getCmp('attacheFileName' + ids).setVisible(true);
	Ext.getCmp('filefield' + ids).setVisible(false);
	Ext.getCmp('delete_file' + ids).setVisible(true);
	Ext.getCmp('download_file' + ids).setVisible(true);
}

/**
 * 添加明细行
 * 
 * @param id
 */
function addDetail(id){
	var grid = Ext.getCmp('applyFormGrid' + id);
	var r;
	if (id == 1) {
		r = Ext.create('HIT.model.ApplyFormInvoiceDetailModel', {
			goodsName : "",
			goodsModel : "",
			goodsUnit : "",
			quantity : "",
			priceUnit : "",
			amount : "",
			taxRate : "",
			taxAmount : ""
        });
	} else {
		r = Ext.create('HIT.model.ApplyFormInvoiceTaxDetailModel', {
			goodsName : "",
			remark : "",
			goodsUnit : "",
			quantity : "",
			priceUnit : "",
			amount : ""
        });
	}
    var store = grid.getStore(); 
    var count = store.getCount();
    store.insert(count, r);
    grid.getView().refresh();
    if (store.getCount() == 0) {
    	Ext.getCmp('del_datail' + id).setVisible(false);
    }else{
    	Ext.getCmp('del_datail' + id).setVisible(true);
    }
}

/**
 * 
 * 删除明细行
 * 
 * @param id
 */
function delDetail(id){
	var grid = Ext.getCmp('applyFormGrid' + id);
	if (grid == undefined) {
		return;
	}
	var cellEdit = null;
	if (id == 1) {
		cellEdit = cellEditing1;
	}else{
		cellEdit = cellEditing2;
	}
	var selModel = grid.getSelectionModel();
	var store = grid.getStore();
	if (selModel.hasSelection()) {
		cellEdit.cancelEdit();
		var selected = selModel.getSelection();
		Ext.each(selected, function(item) {
			grid.getStore().remove(item);
		});
		grid.getView().refresh();
		var count = store.getCount();
		if (count == 0) {
	    	Ext.getCmp('del_datail' + id).setVisible(false);
	    }else{
	    	Ext.getCmp('del_datail' + id).setVisible(true);
	    }
	} else {
		Share.ShowMessage('I0008');
		//Ext.Msg.alert(Share.T('错误'), Share.T('没有任何行被选中，无法进行删除操作！'));
		return;
	}
}

/**
 * 初始化指定表单容器数据
 * 用法：initApplyFormInstance([formNo],[instance])
 * 
 * @param formNo
 * @param instance
 */
function initApplyFormInstance(){
	if(arguments.length <= 0 || arguments.length >= 2){
		return;
	}
	var instance = {};
	if(typeof arguments[0] == "object"){
		instance = arguments[0];
	} else if(typeof arguments[0] == "string"){
		instance = applyFormInstance[arguments[0]];
	}else{
		return;
	}
	// 初始化设置
	instance.applyFormId = 0;
	instance.applyFormState = 0;
	instance.customerId = '';
	instance.applyFormIsUpdated = false;
	//instance.applyFormConfig = null;
	//instance.applyFormPanel = null;
}

/**
 * 当前View验证
 * 
 * @returns {Boolean}
 */
function viewValid(){
    var basicForm = Ext.getCmp("applyform").getForm(); 
    if(!basicForm.isValid()){
        return false;
	}
    return true;
}

// ========================================
// 从str中获取字符串value之后的字符
// @param str
// @param value
// @return {boolean}
// ========================================
function getEndStr (str, value){
	var ret = str.substring(value.length);
	return ret;
}

//========================================
//定义字符串startWith方法
//@param str
//@param value
//@return {boolean}
//========================================
function startWith (str, value){
	var regExp = new RegExp("^" + value,"g");
	var ret = regExp.test(str);
	return ret;
}

// ========================================
// 日期Format处理
// @param value
// ========================================
function dateFormat (value){
	if(value){
		return Ext.Date.format(new Date(value),'Y-m-d');
	}
	return null;
}

//========================================
//表单一览查询按钮
//@param value
//========================================
function searchBtn(id, value){
	if(id.substr(0, id.length - 2) == value) {
		return true;
	} else {
		return false;
	}
}

